//
//  ChannelVC.m
//  CarHome
//
//  Created by 蒋寒霄 on 14-9-19.
//  Copyright (c) 2014年 WJN_work@163.com. All rights reserved.
//

#import "ChannelVC.h"
//Cells
#import "ThreeTableViewCell.h"
#import "OneTableViewCell.h"
//Model
#import "ScrollModel.h"
//VC
#import "RecommendWebVC.h"
#import "AlbumVC.h"


//cell重用池
NSString *const threeCell_Rec = @"ThreeTableViewCell";
NSString *const oneCell_Rec = @"OneTableViewCell";

@interface ChannelVC ()<UITableViewDataSource, UITableViewDelegate>
{
    UITableView *_tabelView;
    NSMutableArray *_arrData;//数组数据
    
    NSString *_firstURL;//传进来的首个地址
    NSMutableString *_channelURL;//可变网址拼接
    int num;
    
    NSString *_title;
    VedioDrawer *_choice;
    BOOL Drawer;
}
@end

@implementation ChannelVC

- (void)dealloc
{
    [_arrData release];
    _arrData = nil;
    [_channelURL release];
    _channelURL = nil;
    [_firstURL release];
    _firstURL = nil;
    [_choice release];
    _choice = nil;
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _arrData = [[NSMutableArray alloc] init];
        _channelURL = [[NSMutableString alloc] init];
        _firstURL = [[NSString alloc] init];
        num = 1;
        _choice = [[VedioDrawer alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor magentaColor];
    // Do any additional setup after loading the view.
    
    UIButton *leftBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBack setFrame:CGRectMake(0, 0, 25, 25)];
    [leftBack setImage:[UIImage imageNamed:@"BackButton.png"] forState:UIControlStateNormal];
    [leftBack addTarget:self action:@selector(leftBackMethod:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBack];
    //创建视图
    [self createTableView];
    [self createChoiceViewDrawer];
    //上拉刷新,下拉加载
    [self setupChannelRefresh];
}
#pragma mark -
#pragma mark createView
- (void)createTableView
{
    _tabelView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    _tabelView.delegate = self;
    _tabelView.dataSource = self;
    _tabelView.showsVerticalScrollIndicator = NO;
    [_tabelView registerClass:[ThreeTableViewCell class] forCellReuseIdentifier:threeCell_Rec];
    [_tabelView registerClass:[OneTableViewCell class] forCellReuseIdentifier:oneCell_Rec];
    [self.view addSubview:_tabelView];
    [_tabelView release];
}
#pragma mark createChoiceDrawer
- (void)createChoiceViewDrawer
{
    _choice = [[VedioDrawer alloc] initWithFrame:CGRectMake(0, -64, self.view.frame.size.width, self.view.frame.size.height)];
    [_choice.background_Button addTarget:self action:@selector(clickDrawer:) forControlEvents:UIControlEventTouchUpInside];
    Drawer = YES;
}

#pragma mark -
#pragma mark ChannelVCsetRefresh 上拉加载下拉刷新
- (void)setupChannelRefresh
{
    [_tabelView addHeaderWithTarget:self action:@selector(headerChannelRefresh)];
    [_tabelView headerBeginRefreshing];// 程序开始就刷新
    [_tabelView addFooterWithTarget:self action:@selector(footChannelRefresh)];
    _tabelView.headerPullToRefreshText = @"下拉刷新";
    _tabelView.headerReleaseToRefreshText = @"释放刷新";
    _tabelView.headerRefreshingText = @"正在刷新中···";
    _tabelView.footerPullToRefreshText = @"上拉加载";
    _tabelView.footerReleaseToRefreshText = @"释放加载";
    _tabelView.footerRefreshingText = @"正在加载中···";
}
#pragma mark 上拉刷新加载方法
- (void)headerChannelRefresh
{
    [self connect:_firstURL];
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_tabelView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tabelView headerEndRefreshing];
        
    });
}
- (void)footChannelRefresh
{
    NSRange subStr = [_channelURL rangeOfString:[NSString stringWithFormat:@"p%d", num]];
    num++;
    if (subStr.location != NSNotFound) {
        [_channelURL replaceCharactersInRange:subStr withString:[NSString stringWithFormat:@"p%d",num]];
    }
    [self connect:_channelURL];
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_tabelView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tabelView footerEndRefreshing];
    });
}
#pragma mark -
#pragma mark tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_arrData count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FoucusImageModel *model = [_arrData objectAtIndex:indexPath.row];
        if ([model.image_mediatype intValue] == 6) {
            return 132;
        } else {
            return 92;
        }
    return 132;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FoucusImageModel *model = [_arrData objectAtIndex:indexPath.row];
        if ([model.image_mediatype intValue] == 6) {
            ThreeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:threeCell_Rec];
            [cell setData:model];
            return cell;
        } else {
            OneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:oneCell_Rec];
            if (model.image_index != 0) {
                [cell createTagLabel:@"推广"];
                cell.tagLabel.backgroundColor = [UIColor redColor];
            } else if ([model.image_mediatype intValue] == 2) {
                [cell createTagLabel:@"说客"];
                cell.tagLabel.backgroundColor = [UIColor orangeColor];
            } else if ([model.image_mediatype intValue] == 3) {
                [cell createTagLabel:@"视频"];
                cell.tagLabel.backgroundColor = [UIColor blueColor];
            } else {
                [cell createTagLabel:@""];
                cell.tagLabel.backgroundColor = [UIColor clearColor];
            }
            [cell setData:model];
            return cell;
        }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FoucusImageModel *model = [_arrData objectAtIndex:indexPath.row];
    if ([model.image_mediatype intValue] == 6) {
        AlbumVC *album = [[AlbumVC alloc] init];
        [album setWithIndexDetail:model.image_indexDetail ID:[model.image_ID intValue]];
        [self presentViewController:album animated:YES completion:^{
            
        }];
        [album release];
        return;
    }
    RecommendWebVC *recommnedWeb = [[RecommendWebVC alloc] init];
    if ([_title isEqualToString:@"说  客"]) {
        [recommnedWeb setWebUrl:[NSString stringWithFormat: shuokeContentURL, [model.image_ID intValue]]];
    } else if ([_title isEqualToString:@"视  频"]) {
        [recommnedWeb setWebUrl:[NSString stringWithFormat: videosContentURL, [model.image_ID intValue]]];
    } else if ([_title isEqualToString:@"最  新"]) {
        if (model.image_index != 0) {
            [recommnedWeb setWebUrl:model.image_urlPath];
        } else if ([model.image_mediatype intValue] == 2) {
            [recommnedWeb setWebUrl:[NSString stringWithFormat: shuokeContentURL, [model.image_ID intValue]]];
        } else if ([model.image_mediatype intValue] == 3) {
            [recommnedWeb setWebUrl:[NSString stringWithFormat: videosContentURL, [model.image_ID intValue]]];
        } else if ([model.image_mediatype intValue] == 5 || [model.image_mediatype intValue] == 4) {
            [recommnedWeb setWebUrl:[NSString stringWithFormat: forumContentURL, [model.image_ID intValue]]];
        } else {
            [recommnedWeb setWebUrl:[NSString stringWithFormat:NewsContentURL, [model.image_ID intValue]]];
        }
    } else {
        [recommnedWeb setWebUrl:[NSString stringWithFormat:NewsContentURL, [model.image_ID intValue]]];
    }
    [self.navigationController pushViewController:recommnedWeb animated:YES];
    [recommnedWeb release];
}
#pragma mark -
#pragma mark 隐藏tabBar
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    [self.tabBarController.tabBar setHidden:YES];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self.tabBarController.tabBar setHidden:NO];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.tabBarController.tabBar setHidden:YES];
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    [self.tabBarController.tabBar setHidden:NO];
}

#pragma mark -
#pragma mark 传值方法
- (void)sendData:(NSMutableArray *)arr url:(NSString *)urlStr title:(NSString *)title
{
    _firstURL = [[NSString alloc] initWithString:urlStr];
    _channelURL = [[NSMutableString alloc] initWithFormat:@"%@", urlStr];
    [_arrData addObjectsFromArray:arr];
    self.navigationItem.title = title;
    _title = title;
    //行情页和视频页有抽屉
    if ([title isEqualToString:@"行  情"] || [title isEqualToString:@"视  频"]) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 25, 25);
        [button setImage:[UIImage imageNamed:@"DrawerButton.png"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(clickDrawer:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
    }
    if ([title isEqualToString:@"最  新"]) {
        [self connetGeneralize];
    }
    [_tabelView reloadData];
}
#pragma mark -
#pragma mark button的点击事件
#pragma mark 行情和视频,导航栏上右button的点击事件
- (void)clickDrawer:(id)sender
{
    if ([_title isEqualToString:@"视  频"] ) {
        if (Drawer == YES) {
            [self.view addSubview:_choice];
            Drawer = NO;
            [_choice setVedioDrawerBlock:^(NSString *urlStr) {
                [_arrData removeAllObjects];
                [self connect:urlStr];
                [_tabelView reloadData];
            }];
            [_choice release];
        } else if (Drawer == NO) {
            [_choice removeFromSuperview];
            [self createChoiceViewDrawer];
        }
    }
}
#pragma mark leftBackMethod
- (void)leftBackMethod:(id)sender
{
    [self.tabBarController.tabBar setHidden:NO];
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark 网络请求
- (void)connect:(NSString *)strURL
{
    [NetUrl connect:strURL parmater:nil Block:^(NSData *data) {
        NSDictionary *dictionary = (NSDictionary *)data;
        NSMutableDictionary *dic = [dictionary objectForKey:@"result"];
        //普通数据类型
        NSRange range = [strURL rangeOfString:@"newslist"];
        NSRange rangeMoive = [strURL rangeOfString:@"videos"];
        if (range.location != NSNotFound) {
            ScrollModel *newsListModel = [ScrollModel returnModelArrayWithNewsList:dic];
            [_arrData addObjectsFromArray:newsListModel.newslist];
        } else if (rangeMoive.location != NSNotFound) {
            ScrollModel *moiveModel = [ScrollModel returnArrayWithMovie:dic];
            [_arrData addObjectsFromArray:moiveModel.vediosList];
        } else {
            ScrollModel *shuoKeModel = [ScrollModel returnArrayWithPersuader:dic];
            [_arrData addObjectsFromArray:shuoKeModel.shuoKeList];
        }

        [_tabelView reloadData];
        
        [_tabelView headerEndRefreshing];
        [_tabelView footerEndRefreshing];
    }];
}
#pragma mark 推广网络请求
- (void)connetGeneralize
{
    [NetUrl connect:GeneralizeURL parmater:nil Block:^(NSData *data) {
        NSDictionary *dictionary = (NSDictionary *)data;
        NSMutableDictionary *dic = [dictionary objectForKey:@"result"];
        ScrollModel *model = [ScrollModel returnArrayWithGeneralizeAD:dic];
        for (FoucusImageModel *generalize in model.newslist) {
            NSInteger index = generalize.image_index;
            [_arrData insertObject:generalize atIndex:index];
        }
    }];
}

#pragma mark -
#pragma mark 视图已经消失
- (void)viewDidDisappear:(BOOL)animated
{
//    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark -
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
